﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;
using FetchDataSystem.DAL;
using FetchDataSystem.Model;

namespace FetchDataSystem
{
    public partial class FrmFetchData : Form
    {
        List<Thread> threads = new List<Thread>();
        double decaptitatingWeight = 0;//读取的重量
        string employeeNo = null;//读取卡号
        int error = 0;//标准误差
        double standardWeight = 0;//标准重量
        public FrmFetchData()
        {
            InitializeComponent();
        }
        //去头工站称重刷卡
        private void BtnDepWeight_Click(object sender, EventArgs e)
        {
            //创建线程1读取重量
            Thread slave1 = new Thread(new ThreadStart(GetHeadWeight));
            slave1.IsBackground = true;
            slave1.Start();
            //创建线程2读取卡号并保存记录
            Thread slave2 = new Thread(new ParameterizedThreadStart(SaveWeightRecord));
            slave2.IsBackground = true;
            slave2.Start("去头");
            //添加到线程集合
            threads.Add(slave1);
            threads.Add(slave2);
        }
        //读取去头重量
        private void GetHeadWeight()
        {
            try
            {
                SerialPort com5 = new SerialPort("com5", 9600, Parity.Even, 8, StopBits.One);
                com5.Open();
                string temp = ModBus.ModBusRead(com5);
                //重量只放在一个寄存器中，需要去掉后面九个寄存器的值
                temp = temp.Substring(0, temp.Length - 9);
                decaptitatingWeight = Convert.ToDouble(temp);
                com5.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //读取卡号，保存称重记录
        private void SaveWeightRecord(object cellName)
        {
            //1.读取刷卡卡号
            try
            {
                SerialPort com7 = new SerialPort("com7", 9600, Parity.Even, 8, StopBits.One);
                com7.Open();
                employeeNo = ModBus.ModBusRead(com7);
                com7.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //2.判断是否上岗
            //根据卡号获得在岗记录
            MountGuard mountGuard = MountGuardService.GetMountGuardByEmplloyeeNo(employeeNo);
            if (mountGuard == null)
            {
                MessageBox.Show("该卡对应的员工没有上岗，请处理错误！", "提示");
                return;
            }
            //3.判断工位是否匹配
            if (mountGuard.CellName.IndexOf(cellName.ToString())==-1)
            {
                MessageBox.Show("刷卡错误，该卡与当前的工站和工位不匹配！", "提示");
                return;
            }
            //4.同步数据到窗体控件中
            ShowInfo(cellName.ToString());
            //5.保存采集记录
            //封装数据
            WeightRecords records = new WeightRecords();
            records.Id = Guid.NewGuid().ToString();
            records.CardId = employeeNo;
            records.CreateDate = DateTime.Now;
            records.CreatorId = Session.UserId;
            records.EmployeeId = mountGuard.EmployeeId;
            records.EmployeeName = mountGuard.EmployeeName;
            records.Remarks = null;
            records.Time = DateTime.Now;
            records.Unit = "kg";
            records.Weight = decaptitatingWeight;
            records.WorkCellId = mountGuard.CellId;
            records.WorkCellName = mountGuard.CellName;
            records.UpdateBy = Session.UserId;
            records.UpdateDate = DateTime.Now;
            //获取设备信息
            Equipment equipment = EquipmentService.GetEquipmentByCondition(mountGuard.CellId,null, "bas_electronsteelyard",DictHandle.GetDictLable("equip_type","0001"));
            records.EquipId = equipment.Id;
            records.EquipName = equipment.EquipmentName;
            records.QrCode = equipment.QrCode;
            //调用数据访问层方法
            switch (cellName.ToString())
            {
                case "去头":
                    FetchDataService.InsertDecaptitating(records);
                    break;
                case "挑刺":
                    FetchDataService.InsertRemoveBoneRecords(records);
                    break;
            }
            

        }
        //利用委托在一个线程中控制主线程控件
        private void ShowInfo(string cellName)
        {
            if (this.InvokeRequired)
            {
                Action<string> action = ShowInfo;
                this.BeginInvoke(action,cellName);
            }
            else
            {
                switch (cellName)
                {
                    case "去头":
                        this.lblDepCardId.Text = employeeNo;
                        this.lblDepWeight.Text = decaptitatingWeight.ToString();
                        break;
                    case "挑刺":
                        this.lblBoneCardId.Text = employeeNo;
                        this.lblBoneWeight.Text = decaptitatingWeight.ToString();
                        break;
                }
                
            }
        }

        private void BtnBoneWeight_Click(object sender, EventArgs e)
        {
            //创建线程1读取重量
            Thread slave1 = new Thread(new ThreadStart(GetHeadWeight));
            slave1.IsBackground = true;
            slave1.Start();
            //创建线程2读取卡号并保存记录
            Thread slave2 = new Thread(new ParameterizedThreadStart(SaveWeightRecord));
            slave2.IsBackground = true;
            slave2.Start("挑刺");
            //添加到线程集合
            threads.Add(slave1);
            threads.Add(slave2);
        }

        private void FrmFetchData_FormClosed(object sender, FormClosedEventArgs e)
        {
            //关闭所有线程
            foreach (Thread th in threads)
            {
                th.Abort();
                th.Join();
            }
        }
        //开片和切片工站流水线自动读卡
        private void BtnHack_Click(object sender, EventArgs e)
        {
            //1.判断是开片还是切片，处理相应数据，读取不同的com从端
            string cellName = null;
            string pieces = null;//每盘片数
            SerialPort com = null;
            string flag = (sender as Button).Tag.ToString();

            switch (flag)
            {
                case "cut":
                    cellName = "开片工位";
                    pieces = "six";
                    //创建端口对象
                    com = new SerialPort("com9", 9600, Parity.Even, 8, StopBits.One);
                    break;
                case "piece":
                    cellName = "切片工位";
                    pieces = "ten";
                    //创建端口对象
                    com = new SerialPort("com11", 9600, Parity.Even, 8, StopBits.One);

                    break;
            }
            //读取卡号
            try
            {
                com.Open();
                employeeNo = ModBus.ModBusRead(com);
                com.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //2.判断员工是否上岗
            //根据卡号获得在岗记录
            MountGuard mountGuard = MountGuardService.GetMountGuardByEmplloyeeNo(employeeNo);
            if (mountGuard == null)
            {
                MessageBox.Show("该卡对应的员工没有上岗，请处理错误！", "提示");
                return;
            }
            //3.判断工位是否匹配
            if (mountGuard.CellName.IndexOf(cellName) == -1)
            {
                MessageBox.Show("刷卡错误，该卡与当前的工站和工位不匹配！", "提示");
                return;
            }
            //4.计算从上岗时间开始到现在的总盘数，显示在控件上
            int curCount = FetchDataService.GetCountByEmployeeIdAndTime(mountGuard.EmployeeId, mountGuard.ClockIn, flag);
            curCount++;
            switch (flag)
            {
                case "cut":
                    this.lblHackNum.Text = curCount.ToString();
                    this.lblHackCardId.Text = employeeNo;
                    break;
                case "piece":
                    this.lblPieceNum.Text = curCount.ToString();
                    this.lblPieceCardId.Text = employeeNo;
                    break;
            }
            //5.保存数据
            //封装数据
            CutPieceRecords records = new CutPieceRecords();
            records.Id = Guid.NewGuid().ToString();
            records.CardId = employeeNo;
            records.CreateDate = DateTime.Now;
            records.CreatorId = Session.UserId;
            records.EmployeeId = mountGuard.EmployeeId;
            records.EmployeeName = mountGuard.EmployeeName;
            records.Remarks = null;
            records.Time = DateTime.Now;
            records.Unit = "个";
            records.Counter +=1;
            records.Piececs = Convert.ToInt32(DictHandle.GetDictLable("piece_num", pieces));
            records.WorkCellId = mountGuard.CellId;
            records.WorkCellName = mountGuard.CellName;
            records.UpdateBy = Session.UserId;
            records.UpdateDate = DateTime.Now;
            //获取设备信息
            Equipment equipment = EquipmentService.GetEquipmentByCondition(null,mountGuard.StationId, "bas_cardreader", DictHandle.GetDictLable("equip_type", "0002"));
            records.EquipId = equipment.Id;
            records.EquipName = equipment.EquipmentName;
            records.QrCode = equipment.QrCode;
            //调用数据访问方法
            FetchDataService.InsertCutPieceRecords(records,flag);
        }

        private void BtnPieceWeight_Click(object sender, EventArgs e)
        {
            //1.获得卡号
            try
            {
                SerialPort com13 = new SerialPort("com13", 9600, Parity.Even, 8, StopBits.One);
                com13.Open();
                employeeNo = ModBus.ModBusRead(com13);
                com13.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //2.是否上岗
            //根据卡号获得在岗记录
            MountGuard mountGuard = MountGuardService.GetMountGuardByEmplloyeeNo(employeeNo);
            if (mountGuard == null)
            {
                MessageBox.Show("该卡对应的员工没有上岗，请处理错误！", "提示");
                return;
            }
            //3.判断工位是否匹配
            if (mountGuard.CellName.IndexOf("切片工位") == -1)
            {
                MessageBox.Show("刷卡错误，该卡与当前的工站和工位不匹配！", "提示");
                return;
            }
            //4.获得鱼片重量
            try
            {
                SerialPort com15 = new SerialPort("com15", 9600, Parity.Even, 8, StopBits.One);
                com15.Open();
                employeeNo = ModBus.ModBusRead(com15);
                //只取第一个寄存器的值
                string temp = ModBus.ModBusRead(com15);
                //重量只放在一个寄存器中，需要去掉后面九个寄存器的值
                temp = temp.Substring(0, temp.Length - 9);
                decaptitatingWeight = Convert.ToDouble(temp);
                this.lblPieceWeight.Text = temp;
                com15.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //5.保存记录
            //封装质检记录（计算误差，判断是否合格）
            CutPieceQualityTestingRecords records = new CutPieceQualityTestingRecords();
            records.Id = Guid.NewGuid().ToString();
            records.CardId = employeeNo;
            records.CreateDate = DateTime.Now;
            records.CreateBy = Session.UserId;
            records.EmployeeId = mountGuard.EmployeeId;
            records.EmployeeName = mountGuard.EmployeeName;
            records.Time = DateTime.Now;
            records.Unit = "g";
            records.Weight = decaptitatingWeight;
            records.WorkCellId = mountGuard.CellId;
            records.WorkCellName = mountGuard.CellName;
            records.UpdateBy = Session.UserId;
            records.UpdateDate = DateTime.Now;
            //获取设备信息
            Equipment equipment = EquipmentService.GetEquipmentByCondition(mountGuard.CellId, null, "bas_electronsteelyard", DictHandle.GetDictLable("equip_type", "0001"));
            records.EquipId = equipment.Id;
            records.EquipName = equipment.EquipmentName;
            records.QrCode = equipment.QrCode;

            records.Remarks = null;
            records.Error = decaptitatingWeight - standardWeight;//误差
            if (records.Error < -error || records.Error > error)
            {
                records.Qualified = 1;//不合格
            }
            records.DelFlag = "0";
            //调用数据访问方法
            FetchDataService.InsertCutPieceQualityTestingRecords(records);
        }

        private void FrmFetchData_Load(object sender, EventArgs e)
        {
            //获得切片的标准误差和标准重量
            string result = DictHandle.GetDictLable("quality_testing", "cut_piece_error");
            if (result == null)
            {
                MessageBox.Show("获取字典中标准误差错误！", "提示");
                return;
            }
            error = Convert.ToInt32(result);
            this.lblError.Text = string.Format("标准误差为：±{0}g", error);
            result = DictHandle.GetDictLable("quality_testing", "cut_piece_200g");
            if (result == null)
            {
                MessageBox.Show("获取字典中标准误差错误！", "提示");
                return;
            }
            standardWeight = Convert.ToInt32(result);
            
        }
    }
}
